package cn.edu.zjut.chopper.registry.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.edu.zjut.chopper.constant.Constant;
import cn.edu.zjut.chopper.exception.AlreadyBoundException;
import cn.edu.zjut.chopper.message.RemoteInterface;
import cn.edu.zjut.chopper.name.NameServer;
import cn.edu.zjut.chopper.registry.RegistryContext;

/**
 * Servlet implementation class RegistryHandle
 */
public class AddRemoteInterface extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Log LOG = LogFactory.getLog(AddRemoteInterface.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddRemoteInterface() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		if (isMultipart == false) {
			getServletContext().getRequestDispatcher("/error.jsp").forward(
					request, response);
			if (LOG.isErrorEnabled()) {
				LOG.error("the enctype of the form must be multipart/form-data!");
			}
			return;
		}

		String name = null;
		String url = null;
		String version = null;
		String note = null;
		String interfaceFilePath = null;

		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			@SuppressWarnings("unchecked")
			List<FileItem> fileItems = upload.parseRequest(request);
			Iterator<FileItem> iter = fileItems.iterator();
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					if ("Name".equals(item.getFieldName())) {
						name = item.getString();
					} else if ("Url".equals(item.getFieldName())) {
						url = item.getString();
					} else if ("Version".equals(item.getFieldName())) {
						version = item.getString();
					} else if ("Note".equals(item.getFieldName())) {
						note = item.getString();
					}
				} else {
					String fileName = item.getName();
					if(fileName.contains("\\")){
						interfaceFilePath = request.getServletContext()
						.getRealPath("/")
						+ "registry_test_interface"
						+ fileName.substring(fileName.lastIndexOf("\\"));
					}else{
						interfaceFilePath = request.getServletContext()
						.getRealPath("/")
						+ "registry_test_interface\\"
						+ fileName;
					}
					
					File f = new File(interfaceFilePath);
					if (f.createNewFile()) {
						item.write(f);
					} else {
						getServletContext().getRequestDispatcher("/error.jsp")
								.forward(request, response);
						if (LOG.isErrorEnabled()) {
							LOG.error("the interface file is already existed!");
						}
						return;
					}
				}
			}
		}catch (Exception e) {
			getServletContext().getRequestDispatcher("/error.jsp").forward(
					request, response);
			if (LOG.isErrorEnabled()) {
				LOG.error("fail to upload the interface file:"+e.getMessage());
			}
			return;
		}

		NameServer nameServer = (NameServer) RegistryContext
				.get(Constant.NameServer);
		try {
			nameServer.bind(name, new RemoteInterface(name, version, url,
					interfaceFilePath, note));
		} catch (AlreadyBoundException e) {
			getServletContext().getRequestDispatcher("/error.jsp").forward(
					request, response);
			if (LOG.isErrorEnabled()) {
				LOG.error("the remote interface is already bound: " + name
						+ "|" + version + "|" + url);
			}
			return;
		}

		getServletContext().getRequestDispatcher("/RemoteInterfaceNameView").forward(
				request, response);
	}

}
